from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from models.order import Order
from models.user import User
from extensions import db
import datetime
import random
import string

order_bp = Blueprint('order', __name__)

def generate_order_number():
    prefix = datetime.datetime.now().strftime('%Y%m%d')
    suffix = ''.join(random.choices(string.digits, k=4))
    return f"ORD{prefix}{suffix}"

@order_bp.route('/orders')
@login_required
def order_list():
    # 获取查询参数
    order_number = request.args.get('order_number', '')
    customer_name = request.args.get('customer_name', '')
    order_type = request.args.get('order_type', '')
    status = request.args.get('status', '')
    
    # 构建查询
    query = Order.query
    if order_number:
        query = query.filter(Order.order_number.like(f'%{order_number}%'))
    if customer_name:
        query = query.filter(Order.customer_name.like(f'%{customer_name}%'))
    if order_type:
        query = query.filter(Order.order_type == order_type)
    if status:
        query = query.filter(Order.status == status)
    
    # 分页
    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(Order.created_at.desc()).paginate(
        page=page, per_page=10, error_out=False)
    
    return render_template('order/list.html',
                         pagination=pagination,
                         orders=pagination.items,
                         order_number=order_number,
                         customer_name=customer_name,
                         order_type=order_type,
                         status=status)

@order_bp.route('/orders/add', methods=['GET', 'POST'])
@login_required
def order_add():
    if request.method == 'POST':
        order = Order(
            order_number=generate_order_number(),
            customer_name=request.form.get('customer_name'),
            customer_phone=request.form.get('customer_phone'),
            customer_address=request.form.get('customer_address'),
            order_type=request.form.get('order_type'),
            total_amount=request.form.get('total_amount'),
            notes=request.form.get('notes'),
            created_by_id=current_user.id,
            status='pending'
        )
        
        db.session.add(order)
        db.session.commit()
        flash('订单创建成功', 'success')
        return redirect(url_for('order.order_list'))
        
    return render_template('order/add.html')

@order_bp.route('/orders/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def order_edit(id):
    order = Order.query.get_or_404(id)
    staff_members = User.query.filter(User.role.in_(['logistics', 'researcher'])).all()
    
    if request.method == 'POST':
        order.customer_name = request.form.get('customer_name')
        order.customer_phone = request.form.get('customer_phone')
        order.customer_address = request.form.get('customer_address')
        order.order_type = request.form.get('order_type')
        order.status = request.form.get('status')
        order.total_amount = request.form.get('total_amount')
        order.notes = request.form.get('notes')
        
        assigned_to_id = request.form.get('assigned_to_id')
        if assigned_to_id:
            order.assigned_to_id = assigned_to_id
            
        db.session.commit()
        flash('订单更新成功', 'success')
        return redirect(url_for('order.order_list'))
        
    return render_template('order/edit.html', order=order, staff_members=staff_members)

@order_bp.route('/orders/delete/<int:id>')
@login_required
def order_delete(id):
    order = Order.query.get_or_404(id)
    db.session.delete(order)
    db.session.commit()
    flash('订单删除成功', 'success')
    return redirect(url_for('order.order_list')) 